package com.cn.chaomeng.controller;

import com.cn.chaomeng.constant.WxConstant;
import com.cn.chaomeng.model.UserDo;
import com.cn.chaomeng.model.weixin.User;
import com.cn.chaomeng.service.ExChangeService;
import com.cn.chaomeng.utils.DateUtil;
import com.cn.chaomeng.utils.EmojiFilter;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 范中燊
 * @version V1.0
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: TODO
 * @date ${date} ${time}
 */
@Controller
@RequestMapping("weixin")
public class WxController
{

    private final Logger logger = Logger.getLogger(WxController.class);

    @Autowired
    private ExChangeService exChangeService;

    @RequestMapping("/login")
    public ModelAndView login(@RequestParam String code)
        throws Exception
    {
        Map<String, Object> resMap = new HashMap<String, Object>();

        String openId = null;

        // code换取openID
        try
        {
            openId = WxConstant.getOpenIdByCode(code);
        }
        catch (Exception e)
        {
            logger.error("获取openID失败", e);
            return new ModelAndView("index", resMap);
        }

        // openId获取用户信息
        // openId不为空，获取用户信息
        // 用户信息为空，传openID
        // openID为空，跳转错误页面
        try
        {
            if (StringUtils.isNotEmpty(openId))
            {
                UserDo userDo = exChangeService.getUserDO(openId);
                // 用户不存在，就新建用户
                if (userDo == null)
                {
                    userDo = new UserDo();
                    User user = WxConstant.getWxUser(openId);
                    if (user != null)
                    {
                        if ("0".equals(user.getSubscribe()))
                        {
                            logger.info("未关注公众号，openID：" + openId);
                        }
                        else
                        {
                            String name = user.getNickname();
                            if (StringUtils.isNotEmpty(name) && EmojiFilter.containsEmoji(name))
                            {
                                name = EmojiFilter.filterEmoji(name);
                                if (EmojiFilter.containsEmoji(name))
                                {
                                    name = null;
                                }
                            }
                            userDo.setOpenid(openId);
                            userDo.setCity(user.getCity());
                            userDo.setHeadimgurl(user.getHeadimgurl());
                            userDo.setNike(name);
                            userDo.setSex(user.getSex());
                            userDo.setUsername(name);
                            userDo.setCreateTime(DateUtil.getTimestamp() + "");
                            userDo.setMember("Y");
                            exChangeService.saveUserDO(userDo);
                        }
                    }
                }
            }
            else
            {
                resMap.put("error", "code:500");
                return new ModelAndView("common/error", resMap);
            }
        }
        catch (Exception e)
        {
            logger.error(e.getMessage(), e);
        }
        return new ModelAndView("redirect:/index/show?openId=" + openId);
    }

    @RequestMapping("/test")
    public ModelAndView test(@RequestParam String code)
    {
        Map<String, Object> resMap = new HashMap<String, Object>();

        return new ModelAndView("app/index_ed");
    }
}
